package com.dhecp.project.base.controller;

import com.dhecp.common.annotation.Log;
import com.dhecp.common.annotation.RepeatSubmit;
import com.dhecp.common.core.controller.BaseController;
import com.dhecp.common.core.domain.AjaxResult;
import com.dhecp.common.core.page.TableDataInfo;
import com.dhecp.common.enums.BusinessType;
import com.dhecp.common.utils.StringUtils;
import com.dhecp.common.utils.TypeUtils;
import com.dhecp.core.layui.GridColumnsPropertyModel;
import com.dhecp.core.layui.TreeDataModel;
import com.dhecp.core.layui.TreeDataUtil;
import com.dhecp.framework.util.ShiroUtils;
import com.dhecp.project.base.domain.BaseInfo;
import com.dhecp.project.base.service.BaseInfoService;
import com.dhecp.project.system.domain.SysDictionaryForPageField;
import com.dhecp.project.system.service.SysDictionaryForFieldService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/base/baseinfo")
public class BaseInfoController extends BaseController {

    private String prefix = "base/baseinfo";

    @Autowired
    private BaseInfoService baseInfoService;

    @Autowired
    private TreeDataUtil treeDataUtil;

    @Autowired
    private SysDictionaryForFieldService dictionaryForFieldService;

    @Autowired
    private GridColumnsPropertyModel gridColumnsPropertyModel;


    /**
     * 打开基础数据选择页（弹出窗口）
     * @param vtype 基础数据分项
     * @return ModelAndView
     * @author DH-Xxj
     */
    @GetMapping("/select")
    public ModelAndView baseinfoSelect(@RequestParam Map<String, Object> params){
        ModelAndView mv = this.getModelAndView();
    	params.put("entity", new BaseInfo()); //生成表格gridColumns对应的实体，用于获取实体属性生成表格字段
    	
    	Integer toolBarWidth = 0;
    	params.put("toolBarWidth", toolBarWidth);
    	if(params.get("pagetype") !=null && params.get("pagetype").toString().equalsIgnoreCase("checkbox"))params.put("checkBox", "yes");
        else params.put("radio", "yes");
    	
        if (mv.isEmpty()){
            mv = this.gotoModelAndViewErrorPage(params, "vtype","基础数据分项");
        }
        if (mv.isEmpty()){
            String moduleTable = "TB_baseinfo_" + params.get("vtype");
            moduleTable = (moduleTable.toLowerCase().indexOf("tb_baseinfo_area") == -1 ? moduleTable : "tb_baseinfo_area");
            params.put("moduleTable", moduleTable);
            mv.addObject("vtype", params.get("vtype"));
            mv.addObject("gridColumns", gridColumnsPropertyModel.queryGridColumnsPropertyModel(params));
            mv.addObject("prefix", prefix);
            mv.addObject("moduleTable", moduleTable);
            mv.setViewName("common/select");
        }
        return mv;
    }
    
    /**
     * 打开基础数据列表
     * @param params
     * @return ModelAndView
     * @author DH-Xxj
     */
    @RequiresPermissions("system:base:view")
    @GetMapping()
    public ModelAndView baseinfo(@RequestParam Map<String, Object> params){
        ModelAndView mv = this.getModelAndView();
    	params.put("entity", new BaseInfo()); //生成表格gridColumns对应的实体，用于获取实体属性生成表格字段
    	
    	Subject userSubject = ShiroUtils.getSubject();
    	Integer toolBarWidth = 0;
    	if (userSubject.isPermitted("system:base:delete")){	//当前登录用户主体是否有删除用户的权限
//        	params.put("checkBox", "yes"); //生成表格gridColumns时包含复选
        	toolBarWidth = toolBarWidth + 100;
    	}
    	if (userSubject.isPermitted("system:base:edit")){ //当前登录用户主体是否有修改的权限
    		toolBarWidth = toolBarWidth + 100;
    	}
    	params.put("toolBarWidth", toolBarWidth);
    	
        if (mv.isEmpty()){
            mv = this.gotoModelAndViewErrorPage(params, "moduleTable", "功能唯一标识");
        }
        if (mv.isEmpty()){
            mv = this.gotoModelAndViewErrorPage(params, "vtype","基础数据分项");
        }
        if (mv.isEmpty()){
            if ("TB_baseinfo".toLowerCase().equals(params.get("moduleTable").toString().toLowerCase())){
                String moduleTable = params.get("moduleTable").toString() + "_" + params.get("vtype");
                moduleTable = (moduleTable.toLowerCase().indexOf("tb_baseinfo_area") == -1 ? moduleTable : "tb_baseinfo_area");
                params.put("moduleTable", moduleTable);
            }
            Map<String, Object> dictionaryForFieldMap = new HashMap<String, Object>();
            AjaxResult ajaxResult = new AjaxResult();
            try{
                dictionaryForFieldMap = dictionaryForFieldService.queryFieldAttributesMap(params);
                if (dictionaryForFieldMap.isEmpty()){
                    ajaxResult = AjaxResult.error("未获取到字段属性。");
                }else{
                    ajaxResult = AjaxResult.success("数据获取成功。");
                }
            }
            catch(Exception e){
                ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
            }
        	mv.addObject("moduleTable", params.get("moduleTable").toString());
            mv.addObject("vtype", params.get("vtype"));
            mv.addObject("fields", TypeUtils.mapToJson(dictionaryForFieldMap));
            mv.addObject("ajaxResult", ajaxResult);
            mv.addObject("gridColumns", gridColumnsPropertyModel.queryGridColumnsPropertyModel(params));
            if("area1".equals(params.get("vtype"))){
                mv.setViewName(prefix + "/arealist");
            }else{
                mv.setViewName(prefix + "/baseinfo");
            }
        }
        return mv;
    }

    /**
     * 打开基础数据新增页
     * @param params
     * @return ModelAndView
     * @author DH-Xxj
     */
    @RequiresPermissions("system:base:add")
    @GetMapping("/add")
    public ModelAndView baseInfoAdd(@RequestParam Map<String, Object> params){
        ModelAndView mv = this.getModelAndView();
        if (mv.isEmpty()){
            mv = this.gotoModelAndViewErrorPage(params, "moduleTable","基础数据表标识");
        }
        if (mv.isEmpty()){
            mv = this.gotoModelAndViewErrorPage(params, "vtype","基础数据分项");
        }
        if (mv.isEmpty()){
        	String pguid = "";
        	String pvname = "";
        	if (params.get("pguid") != null && params.get("pguid") != ""){
        		pguid = params.get("pguid").toString();
        	}
        	if (params.get("pvname") != null && params.get("pvname") != ""){
        		pvname = params.get("pvname").toString();
        	}
        	params.put("entity", new BaseInfo());
            AjaxResult ajaxResult = new AjaxResult();
    		List<SysDictionaryForPageField> dicFieldsList = new ArrayList<SysDictionaryForPageField>(); //字段字典
    		List<Map<String, Object>> fieldsListTemp = new ArrayList<Map<String, Object>>(); //临时存储区，用于存放需要放到最后生成的控件，如：备注等大文本控件
            List<Object> fieldsList = new ArrayList<Object>(); 			//生成控件的字段和属性
            List<Object> fieldsHiddenList = new ArrayList<Object>(); 	//隐藏的字段和属性
        	try{
            	params.put("getFieldAttributesType", "pagenotingrid"); 	//非表格字段
        		dicFieldsList = dictionaryForFieldService.queryFieldAttributesList(params);
                if (dicFieldsList.isEmpty()){
                    ajaxResult = AjaxResult.error("未获取到字段属性。");
                }else{
                    ajaxResult = AjaxResult.success("数据获取成功。");
                    BaseInfo baseInfo = new BaseInfo();
                    baseInfo.setBdefault(false);
                    baseInfo.setBdeleted(false);
                    baseInfo.setFvalue(0.0);
                    baseInfo.setIid(0);
                    baseInfo.setPguid(pguid);
                    baseInfo.setPguidName(pvname);
                    baseInfo.setvAccount("");
                    baseInfo.setvAccountName("");
                    baseInfo.setvCID("");
                    baseInfo.setVid("");
                    baseInfo.setVname("");
                    baseInfo.setVremark("");
                    baseInfo.setVtype(params.get("vtype").toString());
                	for (SysDictionaryForPageField dicFields : dicFieldsList){
                		Map<String, Object> fieldsListMap = TypeUtils.entityToMap(dicFields);
                		Map<String, Object> baseInfoMap = TypeUtils.entityToMap(baseInfo);
                		fieldsListMap.put("fieldContent", baseInfoMap.get(fieldsListMap.get("fields")));
                		
                		if (fieldsListMap.get("fieldFrontType") == null){
                			fieldsListMap.put("fieldFrontType", "t_text");
                		}
                		
                		if ("t_textarea".equals(fieldsListMap.get("fieldFrontType").toString())){ //大文本控件放入临时存储区
                			fieldsListTemp.add(fieldsListMap);
                		}else if ((Integer)fieldsListMap.get("fieldFrontTop") == 1){	//显示的字段
                			fieldsList.add(TypeUtils.mapToJson(fieldsListMap));
                		}else if ((Integer)fieldsListMap.get("fieldFrontTop") == 2){	//隐藏的字段
                			fieldsHiddenList.add(TypeUtils.mapToJson(fieldsListMap));
                		}
                	}
                	if (!fieldsListTemp.isEmpty() && fieldsListTemp.size() > 0){
                		for (Map<String, Object> fieldsMap : fieldsListTemp){ 			//大文本控件追加到数组末尾
                			if ((Integer)fieldsMap.get("fieldFrontTop") == 1){			//显示的字段
                    			fieldsList.add(TypeUtils.mapToJson(fieldsMap));
                    		}else if ((Integer)fieldsMap.get("fieldFrontTop") == 2){	//隐藏的字段
                    			fieldsHiddenList.add(TypeUtils.mapToJson(fieldsMap));
                    		}
                		}
                	}
                }
                mv.addObject("fieldsList", fieldsList);				//显示的字段
                mv.addObject("fieldsHiddenList", fieldsHiddenList);	//隐藏的字段
                mv.addObject("vtype", params.get("vtype"));
        	}catch(Exception e){
        		ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        	}
            mv.addObject("ajaxResult", ajaxResult);
            mv.setViewName(prefix + "/baseinfo_add");
        }
        return mv;
    }

    /**
     * 打开基础数据编辑页
     * @param params
     * @return ModelAndView
     * @author DH-Xxj
     */
    @RequiresPermissions("system:base:edit")
    @GetMapping("/edit")
    public ModelAndView baseInfoEdit(@RequestParam Map<String, Object> params){
        ModelAndView mv = this.getModelAndView();

        if (mv.isEmpty()){
            mv = this.gotoModelAndViewErrorPage(params, "moduleTable","基础数据表标识");
        }
        if (mv.isEmpty()){
            mv = this.gotoModelAndViewErrorPage(params, "guid","整表唯一标识");
        }
        if (mv.isEmpty()){
        	params.put("entity", new BaseInfo());
            AjaxResult ajaxResult = new AjaxResult();
    		List<SysDictionaryForPageField> dicFieldsList = new ArrayList<SysDictionaryForPageField>(); //字段字典
    		List<Map<String, Object>> fieldsListTemp = new ArrayList<Map<String, Object>>(); //临时存储区，用于存放需要放到最后生成的控件，如：备注等大文本控件
            List<Object> fieldsList = new ArrayList<Object>(); 			//生成控件的字段和属性
            List<Object> fieldsHiddenList = new ArrayList<Object>(); 	//隐藏的字段和属性
        	try{
            	params.put("getFieldAttributesType", "pagenotingrid"); 	//非表格字段
        		dicFieldsList = dictionaryForFieldService.queryFieldAttributesList(params);
                if (dicFieldsList.isEmpty()){
                    ajaxResult = AjaxResult.error("未获取到字段属性。");
                }else{
                    BaseInfo baseInfo = baseInfoService.queryBaseInfoByGuid(params.get("guid").toString());
                    if (baseInfo == null){
                        ajaxResult = AjaxResult.error("没有符合条件的数据。");
                    }else{
                        ajaxResult = AjaxResult.success("查询成功。");
                    	for (SysDictionaryForPageField dicFields : dicFieldsList){
                    		Map<String, Object> fieldsListMap = TypeUtils.entityToMap(dicFields);
                    		Map<String, Object> baseInfoMap = TypeUtils.entityToMap(baseInfo);
                    		fieldsListMap.put("fieldContent", baseInfoMap.get(fieldsListMap.get("fields")));
                    		
                    		if (fieldsListMap.get("fieldFrontType") == null){
                    			fieldsListMap.put("fieldFrontType", "t_text");
                    		}
                    		
                    		if ("t_textarea".equals(fieldsListMap.get("fieldFrontType").toString())){ //大文本控件放入临时存储区
                    			fieldsListTemp.add(fieldsListMap);
                    		}else if ((Integer)fieldsListMap.get("fieldFrontTop") == 1){	//显示的字段
                    			fieldsList.add(TypeUtils.mapToJson(fieldsListMap));
                    		}else if ((Integer)fieldsListMap.get("fieldFrontTop") == 2){	//隐藏的字段
                    			fieldsHiddenList.add(TypeUtils.mapToJson(fieldsListMap));
                    		}
                    	}
                    	if (!fieldsListTemp.isEmpty() && fieldsListTemp.size() > 0){
                    		for (Map<String, Object> fieldsMap : fieldsListTemp){ 			//大文本控件追加到数组末尾
                    			if ((Integer)fieldsMap.get("fieldFrontTop") == 1){			//显示的字段
                        			fieldsList.add(TypeUtils.mapToJson(fieldsMap));
                        		}else if ((Integer)fieldsMap.get("fieldFrontTop") == 2){	//隐藏的字段
                        			fieldsHiddenList.add(TypeUtils.mapToJson(fieldsMap));
                        		}
                    		}
                    	}
                    }
                    mv.addObject("fieldsList", fieldsList);				//显示的字段
                    mv.addObject("fieldsHiddenList", fieldsHiddenList);	//隐藏的字段
                    mv.addObject("pguid", baseInfo.getPguid());
                    mv.addObject("vtype", baseInfo.getVtype());
                    }
        	}catch(Exception e){
        		ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        	}
            mv.addObject("ajaxResult", ajaxResult);
            mv.setViewName(prefix + "/baseinfo_add");
        }
        return mv;
    }

    /**
     * 通过传入的条件查询基础数据列表
     * @param params
     * @return GridDataModel
     * @throws Exception
     * @author DH-Xxj
     */
//    @RequiresPermissions("system:base:list")
    @RequestMapping("/list")
    @ResponseBody
    public TableDataInfo list(@RequestParam Map<String, Object> params) throws Exception{
        List<BaseInfo> list = new ArrayList<BaseInfo>();
        try {
        	if (params.get("vtype") == null || params.get("vtype") == ""){
        		params.put("moduleTable", "TB_baseinfo");
        	}else{
                String vtype = params.get("vtype").toString();
                String moduleTable = "TB_baseinfo_" + vtype;
                moduleTable = (moduleTable.toLowerCase().indexOf("tb_baseinfo_area") == -1 ? moduleTable : "tb_baseinfo_area");
        		params.put("moduleTable", moduleTable);
        	}
            list = baseInfoService.queryBaseInfoList(params);
        } catch (Exception e) {
            e.printStackTrace();
            return getDataTable(this.getExceptionMessage(e).toString());   
        }
        return getDataTable(list);
    }

    /**
     * 通过guid查询基础数据单条记录
     * @param guid
     * @return MessageModel
     * @throws Exception
     * @author DH-Xxj
     */
    @RequestMapping("/lineguid")
    @ResponseBody
    public AjaxResult baseInfolineJson(@RequestParam(required = false, defaultValue = "no", value = "guid") String guid) throws Exception{
        AjaxResult ajaxResult = new AjaxResult();
        try{
            BaseInfo baseInfo = baseInfoService.queryBaseInfoByGuid(guid);
            if (baseInfo == null){
                ajaxResult =  AjaxResult.error("没有符合条件的数据。");
            }else{
                ajaxResult = AjaxResult.success("查询成功。", baseInfo);
            }
        }catch(Exception e){
            ajaxResult =  AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }

    /**
     * 通过基础数据分项（vtype）、基础数据编码（vid）查询基础数据单条记录
     * @param vtype
     * @param vid
     * @return MessageModel
     * @throws Exception
     * @author DH-Xxj
     */
    @RequestMapping("/linevid")
    @ResponseBody
    public AjaxResult baseInfolineJson(@RequestParam(required = false, defaultValue = "no", value = "vtype") String vtype,
                                         @RequestParam(required = false, defaultValue = "no", value = "vid") String vid) throws Exception{
        AjaxResult ajaxResult = new AjaxResult();
        try{
            BaseInfo baseInfo = baseInfoService.queryBaseInfoByVtypeAndVid(vtype,vid);
            if (baseInfo == null){
                ajaxResult =  AjaxResult.error("没有符合条件的数据。");
            }else{
                ajaxResult = AjaxResult.success("查询成功。", baseInfo);
            }
        }catch(Exception e){
            ajaxResult =  AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }


    /**
     * 通过传入的条件查询基础数据树
     * @param params
     * @return TreeDataModel
     * @throws Exception
     * @author DH-Xxj
     */
//    @RequiresPermissions("system:base:list")
    @RequestMapping("/listtreejson")
    @ResponseBody
    public Object baseInfoTreeJson(@RequestParam Map<String, Object> params) throws Exception{
        if (params.get("rootvtype") == null || params.get("rootvtype") == ""){
            //根节点类型，若未传入默认为区域"area"
            params.put("rootvtype", "area1");
        }
        List<TreeDataModel> treeDataModelList = new ArrayList<TreeDataModel>();
        try{
            treeDataModelList = baseInfoService.queryBaseInfoTree(params);
            treeDataModelList = treeDataUtil.dealTreeDataModel(treeDataModelList,treeDataModelList.get(0).getMaxlevels());
        }catch(Exception e){
            return treeDataModelList;
        }
        return treeDataModelList;
    }

    /**
     * 新增基础数据
     * @param baseInfoItems 对应实体类的json格式字符串，示例：[{"key11":"value11","key12":"value12"},{"key21":"value21","key22":"value22"}]
     * @return MessageModel
     * @author DH-Xxj
     */
    @RequiresPermissions("system:base:add")
    @Log(title = "基础数据新增", businessType = BusinessType.INSERT)
    @PostMapping("/addpost")
    @ResponseBody
    public AjaxResult baseInfoAddPost(@RequestParam("baseInfoItems") String baseInfoItems) {
        AjaxResult ajaxResult = new AjaxResult();
        if (StringUtils.isEmpty(baseInfoItems)) {
            return  AjaxResult.error("数据提交失败，必填参数有误！");
        }
        try {
            ajaxResult= baseInfoService.insertBaseInfo(baseInfoItems);
        }catch (Exception e) {
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }

    /**
     * 删除基础数据
     * @param baseInfoItems 对应实体类的json格式字符串，示例：[{"key11":"value11","key12":"value12"},{"key21":"value21","key22":"value22"}]
     * @return MessageModel
     * @author DH-Xxj
     */
    @RequiresPermissions("system:base:delete")
    @Log(title = "基础数据删除", businessType = BusinessType.DELETE)
    @PostMapping("/deletepost")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult baseInfoDeletePost(@RequestParam("baseInfoItems") String baseInfoItems) {
        AjaxResult ajaxResult = new AjaxResult();
        if (StringUtils.isEmpty(baseInfoItems)) {
            return AjaxResult.error("数据提交失败，必填参数有误！");
        }
        try {
            ajaxResult= baseInfoService.deleteBaseInfo(baseInfoItems);
        }catch (Exception e) {
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }

    /**
     * 修改基础数据
     * @param baseInfoItems 对应实体类的json格式字符串，示例：[{"key11":"value11","key12":"value12"},{"key21":"value21","key22":"value22"}]
     * @return MessageModel
     * @author DH-Xxj
     */
    @RequiresPermissions("system:base:edit")
    @Log(title = "基础数据修改", businessType = BusinessType.UPDATE)
    @PostMapping("/editpost")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult baseInfoEditPost(@RequestParam("baseInfoItems") String baseInfoItems) {
        AjaxResult ajaxResult = new AjaxResult();
        if (StringUtils.isEmpty(baseInfoItems)) {
            return AjaxResult.error("数据提交失败，必填参数有误！");
        }
        try {
            ajaxResult= baseInfoService.updateBaseInfo(baseInfoItems);
        }catch (Exception e) {
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }

    /**
     * 修改基础数据默认标志
     * @param baseInfoItems 对应实体类的json格式字符串，示例：[{"key11":"value11","key12":"value12"},{"key21":"value21","key22":"value22"}]
     * @return MessageModel
     * @author DH-Xxj
     */
    @RequiresPermissions("system:base:edit")
    @Log(title = "基础数据修改默认标志", businessType = BusinessType.UPDATE)
    @PostMapping("/editbdefaultpost")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult baseInfoBdefaultEditPost(@RequestParam("baseInfoItems") String baseInfoItems) {
        AjaxResult ajaxResult = new AjaxResult();
        if (StringUtils.isEmpty(baseInfoItems)) {
            return AjaxResult.error("数据提交失败，必填参数有误！");
        }
        try {
            ajaxResult= baseInfoService.updateBaseInfoBdefault(baseInfoItems);
        }catch (Exception e) {
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }

    /**
     * 修改基础数据禁用标志
     * @param baseInfoItems 对应实体类的json格式字符串，示例：[{"key11":"value11","key12":"value12"},{"key21":"value21","key22":"value22"}]
     * @return MessageModel
     * @author DH-Xxj
     */
    @RequiresPermissions("system:base:edit")
    @Log(title = "基础数据修改禁用标志", businessType = BusinessType.UPDATE)
    @PostMapping("/editbdeletedpost")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult baseInfoBdeletedEditPost(@RequestParam("baseInfoItems") String baseInfoItems) {
        AjaxResult ajaxResult = new AjaxResult();
        if (StringUtils.isEmpty(baseInfoItems)) {
            return AjaxResult.error("数据提交失败，必填参数有误！");
        }
        try {
            ajaxResult= baseInfoService.updateBaseInfoBdeleted(baseInfoItems);
        }catch (Exception e) {
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }
}
